package hv.fmw.mvc {
	import hv.fmw.core.command.CommandEvent;
	import hv.fmw.core.command.SequentialCommand;
	import hv.fmw.core.configure.ConfigureCSSCmd;
	import hv.fmw.core.configure.ConfigureCmd;
	import hv.fmw.core.configure.ConfigureFontsCmd;
	import hv.fmw.core.configure.ConfigureXMLCmd;
	import hv.fmw.mvc.control.IController;
	import hv.fmw.mvc.model.Model;
	import hv.fmw.mvc.view.ViewManager;

	import flash.display.Sprite;
	import flash.events.Event;

	/**
	 * @author hvong
	 */
	public class Mvc extends Sprite {
		
		
		
		public function Mvc() {
			
		}
		
		/*
		 * Initialise MVC : set model and controller
		 */
		protected function initialize(model:Model, controller:IController) : void {
			ViewManager.getInstance().init(model);
			controller.init(model);
			setConfigPath();
		}

		/*
		 * Configure paths, fonts, data
		 */
		protected function setConfigPath():void {
			var cmd:ConfigureCmd = new ConfigureCmd(stage);
				cmd.addEventListener(CommandEvent.COMMAND_COMPLETE, configure);
				cmd.execute();
		}
		
		protected function configure(event:Event):void {
			var configureCmd:SequentialCommand = new SequentialCommand();
				configureCmd.addEventListener(CommandEvent.ALL_COMMAND_COMPLETE, build);
				configureCmd.addCommand(new ConfigureCmd(stage));
				configureCmd.addCommand(new ConfigureXMLCmd());
				configureCmd.addCommand(new ConfigureFontsCmd());
				configureCmd.addCommand(new ConfigureCSSCmd());
				configureCmd.execute();
				
			stage.addEventListener(Event.RESIZE, _onResizeHandler);
		}
		
		/*
		 * When stage resize, call resize method to all views which implemented IResisable interface
		 */
		private function _onResizeHandler(event : Event) : void {
			ViewManager.getInstance().resize();
		}
		
		/*
		 * When init and config finished
		 */
		protected function build(event : CommandEvent) : void {
			dispatchEvent(new MvcEvent(MvcEvent.CONFIG_COMPLETE));
		}
	}
}
